<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Explaining as ModelExplaining;
use app\common\model\User;
use app\common\model\UserExplaining;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\DbException;
use think\Request;

/**
 * 申论  （简批，精批）
 * 开通会员 赠送 简批次数
 */

class Explaining extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 检测是否需要弹窗
     * @return void 
     */
    public function checkPopup()
    {
        $user_id = $this->auth->id;
        $info = (new UserExplaining())->where('user_id', $user_id)->find();
        // 检查VIP是否到期
        $vip_is_valid = (new User())->isVipValid($user_id);
        // 初始化返回数据
        $result = [
            'popup' => 0,           // 是否弹窗：0-弹窗，1-不弹窗
            'popup_type' => '',     // 弹窗类型：refined-精批，simple-简批
            'popup_title' => '',    // 弹窗标题
            'popup_content' => '',  // 弹窗内容
            'popup_code' => '',     // 弹窗二维码
            'user_status' => [      // 用户状态信息
                'is_vip' => $vip_is_valid, //是否有vip
                'has_explaining' => !empty($info), //是否有申论资源
                'explaining_type' => $info ? $info->type : null, //简批  精批
                'simple_num' => $info ? $info->simple_num : 0, //简批次数
                'teacher_id' => $info ? $info->teacher_id : 0, //教师ID
                'refined_endtime' => $info ? $info->refined_endtime : 0 //精批到期时间
            ]
        ];
        // 判断是否需要弹窗的逻辑
        if ($this->shouldNotShowPopup($info, $vip_is_valid)) {
            $result['popup'] = 1; // 不弹窗
            $result['popup_title'] = '无需弹窗';
            $result['popup_content'] = '用户已具备相应权限';
        } else {
            // 需要弹窗，确定弹窗类型
            $popup_info = $this->getPopupInfo($info, $vip_is_valid);
            $result = array_merge($result, $popup_info);
        }
        $this->success('获取弹窗状态成功', $result);
    }

    /**
     * 判断是否应该弹窗
     * @param object|null $info 用户申论信息
     * @param bool $vip_is_valid VIP是否有效
     * @return bool true-不弹窗，false-弹窗
     */
    private function shouldNotShowPopup($info, $vip_is_valid)
    {
        // 如果没有申论信息，需要弹窗
        if (empty($info)) {
            return false;
        }

        // 精批类型且未到期，不弹窗
        if ($info->type == 2 && $info->refined_endtime > time() && $info->simple_num > 0 ) {
            return true;
        }

        // 简批类型且有次数且已分配老师，不弹窗
        if ($info->type == 1 && $info->simple_num > 0 && $info->teacher_id != 0) {
            return true;
        }
        
        // 其他情况需要弹窗
        return false;
    }

    /**
     * 获取弹窗信息
     * @param object|null $info 用户申论信息
     * @param bool $vip_is_valid VIP是否有效
     * @return array 弹窗信息
     */
    private function getPopupInfo($info, $vip_is_valid)
    {
        $popup_info = [
            'popup' => 0, // 弹窗
            'popup_type' => '',
            'popup_title' => '',
            'popup_content' => '',
            'popup_code' => ''
        ];
        // 非VIP用户且无申论信息，弹精批弹窗
        if (!$vip_is_valid && empty($info)) {
            $popup_info['popup_type'] = 'refined';
            $popup_info['popup_title'] = '开通精批服务';
            $popup_info['popup_content'] = config('site.refined_con');
            $popup_info['popup_code'] = config('site.refined_code');
        }
        // 简批未分配老师，弹简批弹窗
        elseif ($info && $info->teacher_id == 0 && $info->simple_num > 0) {
            $popup_info['popup_type'] = 'simple';
            $popup_info['popup_title'] = '老师分配';
            $popup_info['popup_content'] = config('site.simple_con');
            $popup_info['popup_code'] = config('site.simple_code');
        }
        // 其他情况弹精批弹窗
        else {
            $popup_info['popup_type'] = 'refined';
            $popup_info['popup_title'] = '开通精批服务';
            $popup_info['popup_content'] = config('site.refined_con');
            $popup_info['popup_code'] = config('site.refined_code');
        }

        return $popup_info;
    }


    /**
     * 发布申论
     * @return void 
     */
    public function add(Request $request)
    {
        $user_id = $this->auth->id;
        $param = $request->param();
        if (!$param['title']) {
            $this->error('请填写标题');
        }
        if (!$param['content']) {
            $this->error('请填写内容');
        }
        # 查询用户申论资源
        $user_explaining = (new UserExplaining())->where('user_id', $user_id)->find();
        if (!$user_explaining) {
            $this->error('用户没有申论资源');
        }
        # 判断是否是精批
        if ($user_explaining->type == 2) {
            if ($user_explaining->refined_endtime < time()) {
                $this->error('精批时间到期');
            }
        }
        # 判断是否是简批
        if ($user_explaining->simple_num <= 0) {
            $this->error('资源次数使用完成');
        }
        Db::startTrans();
        try {
            (new ModelExplaining())->insert([
                'user_id' => $user_id,
                'title' => $param['title'],
                'content' => $param['content'],
                'pic' => $param['pic'],
                'type' => $user_explaining->type,
                'teacher_id' => $user_explaining->teacher_id,
                'status' => '1',
                'createtime' => time(),
            ]);
            # 简批次数减1
            (new UserExplaining())->where('user_id', $user_id)->setDec('simple_num', 1);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('发布申论成功');
    }

    /**
     * 申论列表
     * @return void 
     * @throws HttpResponseException 
     * @throws DbException 
     */
    public function list()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page', 1);
        $status = $this->request->param('status', 1); # 状态:1=待批改,2=已批改
        if (!in_array($status, [1, 2])) {
            $this->error('状态错误');
        }
        $list = (new ModelExplaining())->getList(['user_id' => $user_id, 'status' => $status]);
        $this->success('获取申论列表成功', $list);
    }

    /**
     * 申论详情
     * @return void 
     */
    public function detail(){
        $explaining_id = $this->request->param('explaining_id');
        $info = (new ModelExplaining())->where('id', $explaining_id)->find(); # 申论详情
        $user_id = $this->auth->id;
        $user_info = (new User())->where('id', $user_id)->find(); # 用户信息
        if (!$info) {
            $this->error('申论不存在');
        }
        $this->success('获取申论详情成功', $info);
    }


    /**申论文章 */
    public function articleList(){
        $page = $this->request->param('page', 1);
        $list = Db::name('explaining_article')
        ->where('deletetime IS NULL')
        ->where('status',1)
        ->field('id,title,image,createtime')
        ->paginate();
        $this->success('获取成功', $list);
    }

    /**
     * 申论文章详情
     * @return void 
     */
    public function articleDetail(){
        $id = $this->request->param('id');
        $info = Db::name('explaining_article')->where('id',$id)->find(); # 申论文章详情
        if(!$info){
            $this->error('文章不存在');
        }
        $this->success('获取成功', $info);
    }
}
